package aos.maekawa.entity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import aos.maekawa.exception.AosException;

public class RoutineData {

	public static int n = 0;
	public static int m = 0;
	public static int ia = 0;
	public static int cst = 0;
	public static HashMap<Integer, Vector<Integer>> quorumList = null;

	public static void initialize(String configsFile) throws AosException {
		Properties properties = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(configsFile);
		} catch (FileNotFoundException e) {
			System.out.println("file \"" + configsFile + "\" not found");
			e.printStackTrace();
			throw new AosException(e.getMessage(), e);
		}
		System.out.println("configsFile open success");
		try {
			properties.load(fis);
		} catch (IOException e) {
			System.out.println("configsFile \"" + configsFile
					+ "\" load failed");
			e.printStackTrace();
			throw new AosException(e.getMessage(), e);
		}
		System.out.println("configsFile load success");

		if (properties.getProperty("N") != null) {
			n = Integer.parseInt(properties.getProperty("N"));
			System.out.println("number of node is: " + n);
		} else {
			System.out.println("number of node is: " + n + " (default)");
		}

		if (properties.getProperty("M") != null) {
			m = Integer.parseInt(properties.getProperty("M"));
			System.out.println("number of cs is: " + m);
		} else {
			System.out.println("number of cs is: " + m + " (default)");
		}

		if (properties.getProperty("IA") != null) {
			ia = Integer.parseInt(properties.getProperty("IA"));
			System.out.println("interval between cs is: " + ia);
		} else {
			System.out.println("interval between cs is: " + ia + " (default)");
		}

		if (properties.getProperty("CST") != null) {
			cst = Integer.parseInt(properties.getProperty("CST"));
			System.out.println("cst time is: " + cst);
		} else {
			System.out.println("cst time is: " + cst + " (default)");
		}

		quorumList = new HashMap<Integer, Vector<Integer>>();
		for (int i = 0; i < n; ++i) {
			String propertyName = "R" + i;
			if (properties.getProperty(propertyName) != null) {
				StringTokenizer st = new StringTokenizer(
						properties.getProperty(propertyName), ",");
				Vector<Integer> quorum = new Vector<Integer>();
				System.out.print("quorum for node " + i + " is: ");
				while (st.hasMoreTokens()) {
					int q = Integer.parseInt(st.nextToken());
					quorum.add(q);
					System.out.print(q + ", ");
				}
				System.out.println();
				quorumList.put(i, quorum);
			} else {
				System.err.println("error");
			}
		}
	}
}
